package com.zmx.common.common.config;

import com.zmx.common.utils.id.Id0ddEven;
import com.zmx.core.config.ApplicationContextRegister;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentityGenerator;

import java.io.Serializable;

/**
 * @Description: 自定义主键id生成策略
 * @ClassName: MyIdentityGenerator
 * @Author zhaomxr
 * @Date 2021-12-09 16:21
 */
@Slf4j
public class MyIdentityGenerator extends IdentityGenerator {

    private static Id0ddEven id0ddEven = null;

    @Override
    public Serializable generate(SharedSessionContractImplementor s, Object obj) {
        try {
            if (id0ddEven == null) {
                id0ddEven = (Id0ddEven) ApplicationContextRegister.getApplicationContext().getBean("id0ddEven");
            }
            Long id = id0ddEven.generateId0ddEven();
            if (id != null && id > 0) {
                return (Serializable) id;
            }
        } catch (Exception e) {
            log.error("自定义主键id生成策略失败！", e);
            return super.generate(s, obj);
        }
        return super.generate(s, obj);
    }
}
